import 'package:flutter/material.dart';
import 'package:manual/utils/logger.dart';
import 'package:manual/utils/theme_shared_preference_heiper.dart';

class ThemeProvider extends ChangeNotifier {
  ThemeMode _themeMode = ThemeMode.light;

  ThemeMode get themeMode => _themeMode;

  /// 初始化主题
  Future<void> initializeTheme() async {
    final savedTheme = await ThemeSharedPreferencesHelper.getTheme();
    final newThemeMode = savedTheme == "dark" ? ThemeMode.dark : ThemeMode.light;

    if (_themeMode != newThemeMode) {
      _themeMode = newThemeMode;
      Logger.info("当前主题 $_themeMode", tag: "Theme");
      notifyListeners(); // 仅当主题变化时通知 UI 更新
    }
  }

  /// 切换主题并通知 UI 更新
  Future<void> switchTheme(String theme) async {
    if (theme != "light" && theme != "dark") {
      Logger.error("无效的主题设置：$theme", tag: "ThemeProvider");
      return;
    }

    final newThemeMode = theme == "dark" ? ThemeMode.dark : ThemeMode.light;

    if (_themeMode != newThemeMode) {
      _themeMode = newThemeMode;

      // 更新本地存储
      await ThemeSharedPreferencesHelper.updateTheme(theme);

      // 通知所有监听者
      notifyListeners();
    }
  }
}
